// orderPackage/pages/submitOrder/submitOrder.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    customerName: '',
    customerTel: '',
    customerAddress: '',

    note: '', //备注
    orderList: [], //订单信息
    totalMoney: 0, //总价
    totalPoints: 0, //总积分
    totalNum: 0, //总数
    realMoney: 0, //实际支付金额

    usePointsFlag: true, //使用积分弹窗
    useMoneyFlag: true, //使用积分弹窗

    userResPoints: 0, //用户剩余积分
    userResMoney: 0, //用户剩余余额

    usePoints: 0, //本次支付使用的积分
    useMoney: 0, //本次支付使用的余额

    pointsTip: 0, //选择时显示的积分数
    moneyTip: 0, //选择时显示的余额

    showPop: false,
    usePFlag: 0, // 0 不使用  1 使用
    useMFlag: 0, // 0 不使用  1 使用

    showFlag: '', //  points 选择积分   money 选择余额

    productKind: 0, // 0 积分商品  1 钻石商品

    useDiamond: 0,
    totalPost: 0, //总邮费
    deducePost: 0, //抵扣积分
    realPost: 0, //实际支付邮费

  },

  // 输入框编辑
  inputHandle(e) {
    var str = e.currentTarget.dataset.flag
    var val = e.detail.value
    this.setData({
      [str]: val
    })
    console.log(this.data);
  },

  // 显示弹窗
  showHandle(e) {
    var flag = e.currentTarget.dataset.flag,
      moneyTip = this.data.moneyTip,
      pointsTip = this.data.pointsTip;

    if (flag == 'points') {
      if (this.data.totalPoints > this.data.userResPoints) {
        // 用户积分不足时
        pointsTip = this.data.userResPoints
      } else {
        pointsTip = this.data.totalPoints
      }
      this.setData({
        showPop: true,
        pointsTip
      })
    } else if (flag == 'money') {
      if (this.data.totalMoney > this.data.userResMoney) {
        // 用户余额不足时
        moneyTip = this.data.userResMoney
      } else {
        moneyTip = this.data.totalMoney
      }
      this.setData({
        showPop: true,
        moneyTip
      })
    }

    this.setData({
      showFlag: flag
    })
  },

  toAddress() {
    wx.navigateTo({
      url: '/userPackage/pages/address/address?flag=' + 1,
    })
  },

  // 选择积分
  useHandle(e) {
    var flag = e.currentTarget.dataset.flag,
      showFlag = this.data.showFlag,
      useMoney = this.data.useMoney,
      realMoney = this.data.realMoney;


    if (showFlag == 'points') {
      this.setData({
        showPop: false,
        usePointsFlag: true
      })

      // 设置积分
      if (flag == 1) {
        this.computedPoints(1);
      } else {
        this.computedPoints(0);
      }

    } else if (showFlag == 'money') {
      this.setData({
        showPop: false,
        useMoneyFlag: true,
      })
      // 设置余额
      if (flag == 1) {
        // 使用余额
        this.computedMoney(1);
      } else {
        // 不使用
        this.computedMoney(0);
      }
    }
  },

  // 提交订单
  submitHandle() {
    if (this.data.customerName == '') {
      wx.showToast({
        title: '请选择收货地址',
        icon: 'none'
      })
      return
    }


    if (this.data.useDiamond > this.data.diamondNum) {
      wx.showModal({
        title: '抱歉',
        content: '您的钻石不足，不能兑换',
        confirmText: '获取钻石',
        complete: (res) => {
          if (res.cancel) {}
          if (res.confirm) {
            wx.navigateTo({
              url: '/mainPackage/pages/vipCenter/vipCenter',
            })
          }
        }
      })
      return
    }

    var that = this;

    wx.showModal({
      title: '温馨提示',
      content: '药品类商品若未出现质量问题，概不退换',
      confirmText: '我已知晓',
      complete: (res) => {
        if (res.confirm) {
          var url = app.globalData.url + "ScOrder/addOrder",
            user = app.globalData.user,

            productKind = that.data.productKind,
            obj = {
              customerName: that.data.customerName,
              customerTel: that.data.customerTel,
              customerAddress: that.data.customerAddress,
              // 总金额
              totalMoney: that.data.totalMoney,
              // 总数
              totalNum: that.data.totalNum,
              // 实际支付金额
              realMoney: productKind == 0 ? that.data.realMoney : 0,
              // 使用余额
              usedBalance: productKind == 0 ? that.data.useMoney : 0,
              // 抵扣积分
              deductSource: productKind == 0 ? that.data.usePoints : that.data.useDiamond,
              orderFlag: productKind, //0 普通商品  1 钻石商品
              userId: app.globalData.userId,
              companyId: app.globalData.companyId,
              orderNote: that.data.note,
              orderInfoList: [],
            };

          that.data.orderList.forEach((ele, index) => {
            obj.orderInfoList.push({
              factoryId: ele.selectFormat.factoryId,
              productId: ele.selectFormat.productId,
              formatId: ele.selectFormat.formatId,
              productNum: ele.selectFormat.selectNum,
              productPrice: ele.selectFormat.productPrice,
              productTotal: ele.selectFormat.totalMoney,
              userId: app.globalData.userId,
              companyId: app.globalData.companyId,
              deductScore: ele.usedPoints,
              deductMoney: ele.usedMoney,
              postNum: ele.selectFormat.postNum,
            })
          })

          console.log(obj);

          wx.showLoading({
            title: '',
          })
          app.wxRequestJson(url, obj, res => {
              console.log(res);
              if (res.flag) {
                wx.hideLoading()
                // 钻石商品
                if (productKind == 1) {
                  if (user.vipLevel != 0) {
                    that.uploadUserHandle(1)
                  }
                  wx.showModal({
                    title: '提示',
                    content: '兑换成功',
                    confirmText: '立即查看',
                    cancelText: '继续逛逛',
                    complete: (res) => {
                      if (res.cancel) {
                        wx.redirectTo({
                          url: '/mainPackage/pages/diamondMall/diamondMall',
                        })
                      }
                      if (res.confirm) {
                        wx.redirectTo({
                          url: '/userPackage/pages/order/order?index=' + 1,
                        })
                      }
                    }
                  })
                } else {
                  if (user.vipLevel != 0) {
                    that.uploadUserHandle(2)
                  }
                  if (that.data.realMoney == 0) {
                    wx.showModal({
                      title: '提示',
                      content: '支付成功',
                      confirmText: '立即查看',
                      showCancel: false,
                      complete: (res) => {
                        if (res.confirm) {
                          wx.redirectTo({
                            url: '/userPackage/pages/order/order?index=' + 1,
                          })
                        }
                      }
                    })

                    return
                  }
                  that.payHandle(res.data.orderNum)
                }
              } else {
                wx.showToast({
                  title: '购买失败，请重试',
                  icon: 'none'
                })
              }
            },
            err => {
              console.log(err);
            })
        }
      }
    })




  },

  // 更新用户 积分 余额 累计消耗 等级
  uploadUserHandle(flag) {
    var that = this,
      nextLevelScore = JSON.parse(wx.getStorageSync('nextLevelScore')),
      user = app.globalData.user;
    if (flag == 1) {
      // 购买钻石商品
      user.diamondNum = Number(user.diamondNum) - Number(that.data.useDiamond)
      app.globalData.diamondNum = user.diamondNum
    } else {

      // 购买普通商品
      user.userScore = Number(user.userScore) - Number(that.data.usePoints)
      user.usedPoints = Number(user.usedPoints) + Number(that.data.usePoints)
      user.userBalance = Number(user.userBalance) + Number(that.data.usePoints) - Number(that.data.useMoney)
      // 判断用户是否升级
      try {
        if (user.vipLevel < nextLevelScore[nextLevelScore.length - 1].vipLevelNumber) {
          nextLevelScore.forEach(item => {
            if (user.vipLevel < item.vipLevelNumber && user.usedPoints >= item.nextScore) {
              user.vipLevel = user.vipLevel + 1;
              throw 1;
            }
          })
        }

      } catch (error) {

      }

      app.globalData.userScore = user.userScore
      app.globalData.usedPoints = user.usedPoints
      app.globalData.userBalance = user.userBalance
    }
    app.globalData.user = user
    wx.setStorageSync('user', JSON.stringify(user))
  },


  // 支付
  payHandle(orderNum) {
    var url = app.globalData.url + "pay/wxPay",
      that = this;
    wx.showLoading({
      title: '',
    })
    app.wxRequest(url, {
        openId: app.globalData.openId,
        userId: app.globalData.userId,
        totalMoney: that.data.realMoney,
        orderNum: orderNum,
      }, res => {
        console.log(res);
        if (res.flag) {
          wx.showModal({
            title: '提示',
            content: '支付成功',
            showCancel: false,
            confirmText: '立即查看',
            complete: (res) => {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/userPackage/pages/order/order?index=' + 1,
                })
              }
            }
          })

          return
          var datas = res.data.finalPackage;
          console.log(datas);
          wx.requestPayment({
            "timeStamp": datas.timeStamp,
            "nonceStr": datas.nonceStr,
            "package": datas.package,
            "signType": "RSA",
            "paySign": datas.paySign,
            "success": function (res) {
              console.log(res);
              if (res.errMsg == "requestPayment:ok") {
                //支付成功
                wx.showModal({
                  title: '提示',
                  content: '支付成功',
                  confirmText: '立即查看',
                  showCancel: false,
                  complete: (res) => {
                    if (res.confirm) {
                      wx.redirectTo({
                        url: '/userPackage/pages/order/order?index=' + 1,
                      })
                    }
                  }
                })
              }
            },
            "fail": function (res) {
              console.log(res);
              wx.showToast({
                title: '支付失败,请重试',
                icon: 'none'
              })
            },
            "complete": function (res) {
              console.log(res);
            }
          })

        } else {
          wx.hideLoading()
          wx.showToast({
            title: '支付失败,请重试',
            icon: 'none'
          })
        }
      },
      err => {
        console.log(err);
      })


  },

  cancelHandle() {
    wx.navigateBack()
  },

  getVip(level) {
    console.log(level);
    var url = app.globalData.url + "scVip/getVipLevelList";
    wx.showLoading({
      title: '',
    })
    app.wxRequest(url, {
        companyId: app.globalData.companyId
      }, res => {
        console.log(res);
        if (res.flag) {
          res.data.forEach(item => {
            if (item.vipLevelNumber == level) {
              wx.setStorageSync('nextLevelScore', item.nextScore)
            }
          })
          wx.hideLoading()
        }
      },
      err => {
        console.log(err);
      })

  },

  computedPoints(flag) {
    var orderLists = this.data.orderList;
    var usePoints = 0;
    if (flag == 1) {
      if (this.data.userResPoints == 0) {
        usePoints = 0
      } else if (this.data.totalPoints > this.data.userResPoints) {

        // 用户积分不足时
        usePoints = this.data.userResPoints;
        var len = orderLists.length;
        var residue = 0; //剩余积分
        var usedTotal = 0;
        orderLists.forEach((item, index) => {
          item.usedPoints = 0;
          if (item.productKind != 1) {
            if (index == len - 1) {
              residue = this.data.userResPoints - usedTotal;
              item.usedPoints = residue;
            } else {
              var rebate = Number(item.selectFormat.selectNum * item.selectFormat.productScore)
              item.usedPoints = Math.ceil(this.data.userResPoints * rebate / this.data.totalPoints);
              console.log(item.usedPoints);
              usedTotal += item.usedPoints;
            }
          }
        })
      } else {
        usePoints = this.data.totalPoints;
        orderLists.forEach((item, index) => {
          item.usedPoints = item.selectFormat.selectNum * item.selectFormat.productScore;
        })


      }
    } else {
      orderLists.forEach((item) => {
        item.usedPoints = 0;
      })
    }
    this.setData({
      usePoints, //使用积分
      orderList: orderLists,
      usePFlag: usePoints != 0 ? 1 : 0,
    })
  },

  computedMoney(flag) {
    var orderLists = this.data.orderList;
    var useMoney = 0;

    console.log(this.data.userResMoney);
    if (flag == 1) {

      if (this.data.userResMoney == 0) {
        useMoney = 0;
      } else if ((this.data.totalMoney) > this.data.userResMoney) {
        var len = orderLists.length;
        var residue = 0; //剩余余额
        var usedTotal = 0;
        // 用户余额不足时

        useMoney = this.data.userResMoney
        orderLists.forEach((item, index) => {
          item.usedMoney = 0;
          if (index == len - 1) {
            residue = this.data.userResMoney - usedTotal;
            item.usedMoney = residue;
          } else {
            if (item.productKind != 1) {
              var reta = (item.selectFormat.totalMoney) / this.data.totalMoney;
              item.usedMoney = Math.ceil(this.data.userResMoney * reta);
              usedTotal += item.usedMoney;
            }
          }
        })
      } else {
        useMoney = this.data.totalMoney;
        orderLists.forEach((item, index) => {
          item.usedMoney = item.selectFormat.totalMoney;
        })
      }
    } else {
      orderLists.forEach((item) => {
        item.usedMoney = 0;
      })
    }


    var realMoney = 0,
      realMoney = this.data.totalMoney - useMoney + this.data.totalPost;
    this.setData({
      useMoney, //使用余额
      realMoney, //实际支付金额
      orderList: orderLists,
      useMFlag: useMoney != 0 ? 1 : 0,
    })
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var orderList = JSON.parse(options.order),
      totalMoney = 0,
      totalPoints = 0,
      totalNum = 0,
      userResPoints = app.globalData.userScore,
      userResMoney = app.globalData.userBalance,
      diamondNum = app.globalData.diamondNum,

      productKind = 0,
      useDiamond = 0,
      totalPost = 0;
    orderList.forEach(item => {
      if (item.productKind == 1) {
        useDiamond += item.selectFormat.productScore
      }
      productKind = item.productKind || 0
      totalMoney += item.selectFormat.totalMoney * 1
      totalPoints += item.selectFormat.selectNum * item.selectFormat.productScore
      totalNum += item.selectFormat.selectNum
      item.usedPoints = 0
      item.usedMoney = 0
      totalPost += item.selectFormat.postNum

    })
    this.setData({
      orderList, //商品列表
      totalMoney, //总金额
      totalPoints, //总积分
      totalNum, //总数量
      userResPoints, //用户剩余积分
      userResMoney, // 用户剩余余额


      productKind, // 商品类型  0 积分商品 1 钻石商品
      useDiamond, // 使用钻石
      diamondNum, //用户钻石数
      totalPost,
    })
    console.log(productKind);
    console.log(this.data.orderList);
    this.computedPoints(1);
    this.computedMoney(1);






  },




  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var address = wx.getStorageSync('address') ? JSON.parse(wx.getStorageSync('address')) : wx.getStorageSync('moRenAddress') ? JSON.parse(wx.getStorageSync('moRenAddress')) : ''
    console.log(address);
    if (address != '') {
      this.setData({
        customerName: address.addressName,
        customerTel: address.addressTel,
        customerAddress: address.address1 + address.address2,
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})